package com.mutouren.common.orm.spring;

import java.util.Random;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import com.mutouren.common.utils.StringUtils;

public class MultiDataSource extends AbstractRoutingDataSource {
	
	private static final String slaveKeyFormat = "%s_slave%d";

	@Override
	protected Object determineCurrentLookupKey() {
		DataSource ds = DataSourceSynchronizationManager.getDataSource();
		if (ds == null || StringUtils.isBlank(ds.name())) {
			return null;
		} else {
			if (ds.isSlave()) {
				if (ds.slaveCount() == 1) {
					return String.format(slaveKeyFormat, ds.name(), 0);
				} else if (ds.slaveCount() > 1) {
					return String.format(slaveKeyFormat, ds.name(), new Random().nextInt(ds.slaveCount()));
				} else {
					throw new RuntimeException("DataSourceInfo error: when isSlave = true, slaveCount must > 0");
				}				
			} else {
				return ds.name();
			}				
		}
	}

}
